package com.sdcqjy.property.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.widget.FrameLayout;

import com.sdcqjy.mylibrary.FileOperateUtil;
import com.sdcqjy.mylibrary.OtherUtils;
import com.sdcqjy.mylibrary.http.DownloadCallBack;
import com.sdcqjy.mylibrary.http.DownloadDB;
import com.sdcqjy.mylibrary.http.DownloadManage;
import com.sdcqjy.mylibrary.http.DownloadMode;
import com.sdcqjy.mylibrary.http.DownloadTask;
import com.sdcqjy.mylibrary.widget.ShowToast;
import com.sdcqjy.property.R;
import com.sdcqjy.property.base.SimpleBaseActivity;
import com.sdcqjy.property.presenter.contract.a;
import com.sdcqjy.property.utils.MyIntent;
import com.tencent.smtt.sdk.TbsReaderView;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

/**
 * webView展示页
 */
public class WordActivity extends SimpleBaseActivity implements DownloadCallBack {
    @BindView(R.id.fl)
    FrameLayout fl;
    private DownloadTask downloadTask;
    private String wordUrl;
    private ProgressDialog progressDialog;
    private String path;

    public static void open(Context context, String wordUrl) {
        Intent intent = new Intent(context, WordActivity.class);
        intent.putExtra("wordUrl", wordUrl);
        context.startActivity(intent);
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_word);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        wordUrl = intent.getStringExtra("wordUrl");
    }

    protected void asynRun() {
        if (TextUtils.isEmpty(wordUrl)) {
            finish();
            return;
        }
        checkSDCardPermission();
    }

    /**
     * 打开文件
     */
    private void openFile(String path) {
        this.path = path;
        String[] split = path.split("\\.");
        TbsReaderView readerView = new TbsReaderView(this, new TbsReaderView.ReaderCallback() {
            public void onCallBackAction(Integer integer, Object o, Object o1) {
            }
        });
        mTbsReaderView = readerView;
        //通过bundle把文件传给x5,打开的事情交由x5处理
        Bundle bundle = new Bundle();
        //传递文件路径
        bundle.putString("filePath", path);
        //加载插件保存的路径
        bundle.putString("tempPath", Environment.getExternalStorageDirectory() + File.separator + "temp");
        //加载文件前的初始化工作,加载支持不同格式的插件
        boolean b = readerView.preOpen(split[split.length - 1], false);
        if (b) {
            readerView.openFile(bundle);
        }
        fl.addView(readerView);
    }

    private TbsReaderView mTbsReaderView;

    protected void onDestroy() {
        super.onDestroy();
        if (mTbsReaderView != null) mTbsReaderView.onStop();
        DownloadManage.getInstance().removeCallBack(this);
    }

    @OnClick(R.id.textR)
    public void onViewClicked() {
        if (TextUtils.isEmpty(path)) return;
        //android获取一个用于打开Word文件的intent
        Intent intent;
        //ppt doc xls pdf
        String[] split = path.split("\\.");
        if (split.length == 0) return;
        String ends = split[split.length - 1];
        if (TextUtils.isEmpty(ends)) return;
        if (ends.contains("ppt")) {
            intent = new MyIntent(getActivity()).getPptFileIntent(path);
        } else if (ends.contains("doc")) {
            intent = new MyIntent(getActivity()).getWordFileIntent(path);
        } else if (ends.contains("xls")) {
            intent = new MyIntent(getActivity()).getExcelFileIntent(path);
        } else if (ends.contains("pdf")) {
            intent = new MyIntent(getActivity()).getPdfFileIntent(path);
        } else return;
        List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);
        if (list.size() > 0) {
            ///浏览器存在
            startActivity(intent);
        } else {
            ///浏览器不存在
            ShowToast.alertShortOfWhite(getActivity(), "未能找到打开文档的其他应用");
        }
    }

    private void checkSDCardPermission() {
        if (ContextCompat.checkSelfPermission(getActivity()
                , Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            downloadFile();
        } else {
            PermissionGen.with(getActivity())
                    .addRequestCode(200)
                    .permissions(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    .request();
        }
    }

    @PermissionSuccess(requestCode = 200)
    public void doSDLoadSuccess() {
        downloadFile();
    }

    @PermissionFail(requestCode = 200)
    public void doSDLoadFail() {
        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.tishi)
                .setMessage(R.string.ylwd_qxts)
                .setPositiveButton(R.string.congxinhuoqu, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        checkSDCardPermission();
                    }
                })
                .setNeutralButton(R.string.shoudonghuoqu, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        OtherUtils.startAppDetailSettingIntent(getActivity());
                    }
                }).show();
    }

    private void downloadFile() {
        downloadTask = new DownloadTask(DownloadTask.DownloadTypeStart, a.FileHost + wordUrl);
        downloadTask.setDownloadCallBack(this);
        String name = downloadTask.getName();
        DownloadDB db = new DownloadDB(getActivity());
        List<DownloadMode> modeList = db.getTaskOfName(name);
        db.close();
        String fileName = FileOperateUtil.getFileNameOfUrl(downloadTask.getUrl());
        downloadTask.path = FileOperateUtil.getInstance().getFolderPath(FileOperateUtil.TYPE_TEXT);
        String path = downloadTask.path + fileName;
        if (modeList == null || modeList.size() == 0) {
            File file = new File(path);
            if (file.exists()) openFile(path);
            else {
                DownloadManage.getInstance().executionTask(downloadTask);
                openDialog();
            }
        } else {
            DownloadManage.getInstance().executionTask(downloadTask);
            openDialog();
        }
    }

    private void openDialog() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setMax(100);
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getString(R.string.quxiao), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                progressDialog = null;
                if (downloadTask != null) {
                    downloadTask.setType(DownloadTask.DownloadTypePause);
                    DownloadManage.getInstance().executionTask(downloadTask);
                }
                onBackPressed();
            }
        });
    }

    public void inProgress(DownloadMode mode) {
        if (progressDialog == null) return;
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
        long l = mode.currLen * 100 / mode.total;
        progressDialog.setProgress((int) l);
    }

    public void onError(DownloadMode mode) {
        ShowToast.alertShortOfWhite(getActivity(), R.string.xiazaishibai);
        if (progressDialog == null) return;
        progressDialog.dismiss();
        progressDialog = null;
    }

    public void onStop(DownloadMode mode) {
    }

    public void onResponse(DownloadMode mode) {
        if (progressDialog == null) return;
        progressDialog.dismiss();
        progressDialog = null;
        openFile(mode.path);
    }
}
